package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbDict;
import com.bwie.service.TbDictService;
import com.bwie.mapper.TbDictMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.xml.ws.Action;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Lenovo
* @description 针对表【tb_dict(字典表)】的数据库操作Service实现
* @createDate 2025-07-22 20:06:28
*/
@Service
@Slf4j
public class TbDictServiceImpl extends ServiceImpl<TbDictMapper, TbDict>
    implements TbDictService{

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private TbDictMapper tbDictMapper;

    @PostConstruct
    public void loadDictList(){
        log.info("加载字典开始");
        //List<TbDict> tbDictList = tbDictMapper.selectList(null);
        List<TbDict> tbDictList = list();
        for (TbDict tbDict : tbDictList) {
            String key="dict-"+tbDict.getDictType();
            redisTemplate.opsForList().leftPush(key,JSON.toJSONString(tbDict));
        }
        log.info("加载字典结束");
    }

    @Override
    public R getDictList(PageInfoVo pageInfoVo) {
        Page<TbDict> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        QueryWrapper<TbDict> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByAsc(TbDict::getDictType).orderByAsc(TbDict::getDictValue);
        //Page<TbDict> tbDictPage = tbDictMapper.selectPage(page, wrapper);
        Page<TbDict> tbDictPage = page(page, wrapper);
        return R.OK(tbDictPage);
    }

    @Override
    public R getDictListBytypeId(Integer typeId) {
        String key="dict-"+typeId;
        List<String> stringList = redisTemplate.opsForList().range(key, 0, -1);
        if(stringList!=null && stringList.size()>0){
            List<TbDict> tbDictList = stringList.stream().map(item -> JSON.parseObject(item, TbDict.class)).collect(Collectors.toList());
            return R.OK(tbDictList);
        }

        QueryWrapper<TbDict> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbDict::getDictType,typeId);
        List<TbDict> list = list(wrapper);
        for (TbDict tbDict : list) {
            if(tbDict.getDictType().equals(typeId)){
                redisTemplate.opsForList().leftPush(key,JSON.toJSONString(tbDict));
            }
        }

        return R.OK(list);
    }
}




